﻿using ApiServer.SwaggerExt;
using Common;
using DTOModels;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace ApiServer.Controllers.ServiceAPI
{
    /// <summary>
    /// 文件处理控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    [ApiExplorerSettings(IgnoreApi = false, GroupName = nameof(ApiVersions.V1))]
    public class FileController : ControllerBase
    {
        private readonly ILogger<FileController> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="logger"></param>
        public FileController(ILogger<FileController> logger)
        {
            _logger = logger;
        }

        /// <summary>
        /// 处理文件上传
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> UploadFile([FromForm] UploadFileDto dto)
        {
            var file = dto.File;
            //容易出现图片的名称相同的情况--在同一个文件夹保存不了的
            //1.  把图片重命名
            string suffix = string.Empty;
            #region 获取文件后缀 
            string filename = file.FileName.Trim();
            int index = filename.LastIndexOf(".");
            if (index > 0 && index < filename.Length - 1)
            {
                suffix = filename.Substring(index + 1);
            }
            #endregion

            #region 重新命名保存文件的名字 
            string saveDirectory = $"FileUpload\\{DateTime.Now.ToString("yyyy-MM-dd")}";

            string allSavePath = $"{Directory.GetCurrentDirectory()}\\{saveDirectory}";
            if (Directory.Exists(allSavePath) == false)
            {
                Directory.CreateDirectory(allSavePath); //如果文件夹不存在，创建
            }

            //保存的新文件名--包含后缀的
            string newFileName = $"{DateTime.Now.ToString("yyyyMMddHHmmss")}_{Guid.NewGuid()}.{suffix}";

            //保存的文件名
            string allSaveFilePath = $"{allSavePath}\\{newFileName}";  //带盘符的一个文件的全路径
            #endregion


            try
            {
                using (FileStream stream = System.IO.File.Create(allSaveFilePath))
                {
                    await file.CopyToAsync(stream);
                }
                return new JsonResult(new ApiResultData<string>()
                {
                    Success = true,
                    Message = "文件上传成功",
                    Data = $"{saveDirectory}\\{newFileName}"
                });
            }
            catch (Exception)
            {
                return new JsonResult(new ApiResultData<string>()
                {
                    Success = false,
                    Message = "文件上传失败了"
                });
            }
        }
    }

}
